<%@page import="java.util.List,com.trw.trp.util.*,com.trw.trp.bean.*"%>
<%@ include file="header.jsp"%>

<style type="text/css">  
    .tds {width:130}
	
</style> 

<%
step=0;
OrderBean order = (OrderBean) TRPUtil.getFromSession(TRPConstants.CURRENT_ORDER);
UserBean user = (UserBean) TRPUtil.getFromSession(TRPConstants.CURRENT_USER);
List<ModelBean> modelList = (List<ModelBean>) TRPUtil.getFromSession("modelList");
%>

<table align="center" cellpadding="0" cellspacing="0" id="giTable" height="100%"  width="99.9%" border="0">
	<tr>
		<td valign="top">
			<div id="generalInfoDiv"/>
		</td>
	</tr>
</table>

<script type="text/javascript">

function getSelectedModels(){
	var index,ret="",item,selectedFieldset=Ext.getCmp('selectedFieldset');
	for(index=0;index<selectedFieldset.items.length;index++){
		item = selectedFieldset.items.getAt(index);
		if(item.xtype=='button'){
			var tmp = item.el.dom.innerHTML;
			var end = tmp.indexOf('</font>');
			if(end==-1){
				end = tmp.indexOf('</FONT>');
			}
			tmp = tmp.substring(0,end);
			var start = tmp.lastIndexOf('>');
			ret+=tmp.substr(start+1)+',';
		}
	}
	return ret;
}

var generalInfoPanel,modelStore, modelPanel, i, selectedModePanel;

Ext.onReady(function(){

	// Make the button Draggable inside  tag
	var initDragZone = function(v) {

		v.dragZone = new Ext.dd.DragZone(Ext.getDom('selectedFieldset'), {
			getDragData: function(e) {
				// .button-draggable == class of the button you want to drag around
				if(sourceEl = e.getTarget('.button-draggable')) {
					d = sourceEl.cloneNode(true);
					d.id = Ext.id();
					return v.dragData = {
						sourceEl: sourceEl,
						repairXY: Ext.fly(sourceEl).getXY(),
						ddel: d
					}
				}
			},

			onDrag: function(e) {
				// !Important: manually fix the default position of Ext-generated proxy element
				// Uncomment these line to see the Ext issue
				var proxy = Ext.DomQuery.select('*', this.getDragEl());
				proxy[2].style.position = '';
			},

			getRepairXY: function() {
				return this.dragData.repairXY;
			}
		});
	};		

        // Make the panel droppable to the button
	var initDropZone = function(g) {
		g.dropZone = new Ext.dd.DropZone(g.body, {

			getTargetFromEvent: function(e) {
				return e.getTarget('#selectedFieldset');
			},

			onNodeOver : function(target, dd, e, data){
				return Ext.dd.DropZone.prototype.dropAllowed;
			},

			onNodeDrop : function(target, dd, e, data) {
				// !Important: We assign the dragged element to be set to new drop position
				if(dragEl = Ext.get(data.sourceEl)) {
					dragEl.setXY([e.getPageX(),e.getPageY()]);
				}
				var panel = Ext.getCmp(dd.id);
				var items = panel.items;
				var idx = -1;
				var btn = Ext.getCmp(data.sourceEl.id);
				var idx0 = items.indexOf(btn);
				for(var i=0;i<items.length;i++){
					if(items.getAt(i).getEl().getX()>btn.getEl().getX()){
						idx = i;
						break;
					}
				}
				
				if(idx == -1){
					idx = items.length-1;
				}
				panel.move(idx0,idx);
				panel.setHeight(160);
				panel.doLayout();
				return true;
			}	

		});
	};
	
	var addSelectModel=function(selectedModelPanel,htmlText){
		var	item3 = Ext.create('Ext.Button', {
			width:150,
			height:200,
			cls: 'button-draggable',
			listeners: {
				render: initDragZone
			},
			style: {
				marginLeft:'10px', 
				marginRight:'10px',
				marginTop:'10px'
			},
			text: htmlText
		});
		/*if(selectedModelPanel.items.length>1){
			label = Ext.create('Ext.panel.Panel',{
				width: 50,
				height: 60,
				border:0,
				style: {
					marginLeft:'15px', 
					marginRight:'0px',
					marginTop:'50px'
				},
				bodyStyle:{"background-color":"#DFE9F6"}, 
				items: [{
					xtype: 'label',
					html:'<img height="30" width="30" src="images/arrow.gif">'
				}]
			});
			selectedModelPanel.add(label);
		}*/
		selectedModelPanel.removeAll(true);
		selectedModelPanel.add(item3);
		selectedModelPanel.doLayout();
		item3.getEl().on('click',function(){
			/*var idx = selectedModelPanel.items.indexOf(item3);
			if(idx>1){
				selectedModelPanel.remove(selectedModelPanel.items.getAt(idx-1));
			}
			selectedModelPanel.remove(item3);*/
			selectedModelPanel.removeAll(true);
			selectedModelPanel.doLayout();
		});
	}
		
	Ext.define('users', {
		extend: 'Ext.data.Model',
		fields: ['userId', 'name','tel','mobile']
	});
	
	if(!generalInfoPanel){
		generalInfoPanel = Ext.create('Ext.form.Panel', {
			url: 'selectSubModel.action',
			border:false,
			frame:true,
			//width: Ext.getBody().getWidth(),
			renderTo: 'generalInfoDiv',
			layout: 'column',
			items:[{
				xtype:'fieldset',
				title: '<font size=3><b>General Information</b></font>',
				width: Ext.getBody().getWidth()-35,
				//minWidth:800,
				autoScroll:true,
				layout: {
					type: 'table',
					columns: 4,
					tableAttrs: {
						border:1,
						cellspacing:0,
						cellpadding:0,
						bordercolor:'white',
						style: {
							width: '100%'
						}
					}
				},
				//border:false,
				defaultType: 'textfield',
				defaults: {
					labelWidth:130
				},
				items:[{
					colspan:2,
					xtype: 'displayfield',
					fieldLabel: 'TRP Number',
					cellCls:'tds',
					value: '<%=order.getOrderNumber()%>'
				},{
					rowspan:4,
					fieldLabel: 'Project Name',
					cellCls:'tds',
					labelSeparator:'',
					xtype: 'displayfield'
				},{
					xtype:'combo',
					fieldLabel: '<b>Customer *</b>',
					allowBlank:false,
					id:'customerSelect',
					name:'customerSelect',
					displayField: 'name',
					valueField: 'name',
					typeAhead:true,
					autoScroll:true,
					width:'auto',
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=1',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					})
				},{
					colspan:2,
					xtype: 'displayfield',
					fieldLabel: 'Created Date',
					cellCls:'tds',
					value: '<%=TRPConstants.DATE_FORMAT.format(order.getCreatedDate())%>'
				},{
					xtype:'combo',
					fieldLabel: '<b>Project *</b>',
					allowBlank:false,
					id:'projectSelect',
					name:'projectSelect',
					typeAhead:true,
					autoScroll:true,
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=2',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					displayField: 'name',
					valueField: 'name'
				},{
					colspan:2,
					xtype:'combo',
					fieldLabel: '<b>Phase *</b>',
					allowBlank:false,
					id:'phaseSelect',
					name:'phaseSelect',
					typeAhead:true,
					autoScroll:true,
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=4',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					displayField: 'name',
					valueField: 'name'
				},{
					xtype:'combo',
					fieldLabel: '<b>Product *</b>',
					allowBlank:false,
					id:'productSelect',
					name:'productSelect',
					typeAhead:true,
					autoScroll:true,
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: [{type: 'string', name: 'name'}],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=3',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					displayField: 'name',
					valueField: 'name'
				},{
					colspan:2,
					allowBlank:false,
					id:'testPurpose',
					name:'testPurpose',
					xtype:'textarea',
					height:50,
					width: 400,
					fieldLabel: '<b>Test Purpose *</b>'
				},{
					xtype:'combo',
					fieldLabel: '<b>Plant *</b>',
					allowBlank:false,
					id:'plantSelect',
					name:'plantSelect',
					typeAhead:true,
					autoScroll:true,
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: [{type: 'string', name: 'name'}],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=7',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					displayField: 'name',
					valueField: 'name'
				},{
					rowspan:2,
					labelSeparator:'',
					xtype: 'displayfield',
					fieldLabel: 'Applicant',
					labelWidth:100,
					cellCls:'tds'
				},{
					xtype: 'displayfield',
					fieldLabel: 'Name',
					value: '<%=user.getName()%>'
				},{
					xtype:'panel',
					colspan:2,
					bodyStyle:{"background-color":"#DFE9F6"}, 
					border:false,
					layout:'hbox',
					items:[{
						xtype:'textfield',
						fieldLabel: '<b>Project Number *</b>',
						labelWidth:130,
						allowBlank:false,
						id:'prjNumber',
						name:'prjNumber'
					},{
						xtype:'label',
						text:'(format:PRxxxxx)'
					}]
				},{
					xtype: 'displayfield',
					fieldLabel: 'Mobile/Tel',
					value: 'Tel:'+'<%=user.getTel()%>'+' Mobile:'+'<%=user.getMobile()%>'
				},{
					xtype:'combo',
					colspan:2,
					fieldLabel: '<b>Payer *</b>',
					id:'payer',
					name:'payer',
					allowBlank:false,
					editable:false,
					displayField: 'name',
					valueField: 'name',
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=24',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					})
				},{
					xtype: 'displayfield',
					fieldLabel: 'Test Engineer',
					cellCls:'tds',
					rowspan:2,
					labelSeparator:''
				},{
					xtype:'combo',
					fieldLabel: '<b>Name *</b>',
					id:'testUserSelect',
					name:'testUserSelect',
					allowBlank:false,
					editable:false,
					queryMode: 'local',
					store: Ext.create('Ext.data.Store', {
						autoLoad:true,
						model: 'users',
						proxy : new Ext.data.HttpProxy( {
							type: 'ajax',
							url : 'getUsers.action',
							extraParams:{position:'Test Engineer',department:'OSS'},
							reader: {
								type: 'json',
								totalProperty : 'size',
								root : 'items',
								idProperty: 'userId'
							}
						})
					}),
					displayField: 'name',
					valueField: 'userId',
					listeners:{
						"select":function(combo,records,eOpts ){
							var v = records[0].data;
							var e = Ext.getCmp("testUserTel");
							e.setValue('Tel:'+v.tel+' Mobile:'+v.mobile);
						}
					}
				},{
					xtype:'combo',
					colspan:2,
					fieldLabel: '<b>Report mode *</b>',
					allowBlank:false,
					id:'reportModeSelect',
					name:'reportModeSelect',
					queryMode: 'local',
					editable:false,
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=5',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					displayField: 'name',
					valueField: 'name'
				},{
					xtype: 'displayfield',
					fieldLabel: 'Mobile/Tel',
					id:'testUserTel'
				},{
					xtype:'combo',
					colspan:2,
					fieldLabel: '<b>Report distribution *</b>',
					allowBlank:false,
					id:'reportDistrSelect',
					name:'reportDistrSelect',
					editable:false,
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=6',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					displayField: 'name',
					valueField: 'name'
				},{
					xtype: 'displayfield',
					fieldLabel: 'V&V Engineer',
					cellCls:'tds',
					rowspan:2,
					labelSeparator:''
				},{
					xtype:'combo',
					fieldLabel: '<b>Name *</b>',
					allowBlank:false,
					id:'vvUserSelect',
					name:'vvUserSelect',
					editable:false,
					queryMode: 'local',
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						model: 'users',
						proxy : new Ext.data.HttpProxy( {
							type: 'ajax',
							url : 'getUsers.action',
							extraParams:{position:'V&V Engineer',department:'OSS'},
							reader: {
								type: 'json',
								totalProperty : 'size',
								root : 'items',
								idProperty: 'userId'
							}
						})
					}),
					displayField: 'name',
					valueField: 'userId',
					listeners:{
						"select":function(combo,records,eOpts ){
							var v = records[0].data;
							var e = Ext.getCmp("vvUserTel");
							e.setValue('Tel:'+v.tel+' Mobile:'+v.mobile);
						}
					}
				},{
					xtype:'label',
					colspan:2
				},{
					xtype: 'displayfield',
					fieldLabel: 'Mobile/Tel',
					id:'vvUserTel',
					labelWidth:60,
					width:250
				},{
					xtype:'label',
					colspan:2
				}]
			},{
				xtype:'fieldset',
				id:'modelFieldset',
				bodyPadding: 5,
				width: Ext.getBody().getWidth()-35,
				minWidth:600,
				height: 270,
				title: '<font size=3><b>Select Test Type:</b></font><font size=2>(* please select at least one test type)</font>',
				layout: {
					type: 'table',
					rows: 1
				},
				autoScroll:true
			},{
				xtype:'fieldset',
				bodyPadding: 0, 
				height: 270,
				width: Ext.getBody().getWidth()-35,
				minWidth:600,
				autoScroll:true,
				layout: {
					type: 'table',
					rows: 1
				},
				id: 'selectedFieldset',
				listeners: {
					render: initDropZone
				},
				items: [{
					label:''
				}],
				title: '<font size=3><b>Select Test Sequence:</b></font>'
			}],
			buttonAlign:'center',
			buttons:[{
				text:'Save',
				cls:'big-button',
				id:'btnSave',
				handler: function() {
					var ret = getSelectedModels();
					Ext.getBody().mask('processing...');
					generalInfoPanel.getForm().submit({
						clientValidation: false,
						method:'POST',
						params:{
							models:ret
						},
						success : function(from, action) {
							Ext.getBody().unmask();
							flashMessage('data saved.','btnSave',1500);
						},
						failure : function(form, action) {
							Ext.getBody().unmask();
							Ext.MessageBox.alert('Warning', 'save failed, please try again.');
						}
					});
				}
			},{
				text: 'Next',
				cls:'big-button',
				handler: function() {
					if(!generalInfoPanel.getForm().isValid()){
						Ext.Msg.alert('Warning', 'Please fill in all the fields!');
						return false;
					}
					var ret = getSelectedModels();
					if(ret==''){
						Ext.Msg.alert('Warning', 'Please select models!');
						return false;
					}
					Ext.MessageBox.confirm('Confirm', 'All the information in this page will be frozen after your confirmation! Still want to continue?', function(btn){
						if(btn=='yes'){
							Ext.getBody().mask('processing...');
							generalInfoPanel.getForm().submit({
								method:'POST',
								params:{
									models:ret
								},
								success : function(from, action) {
									Ext.getBody().unmask();
									document.location='goSubModel.action';
								},
								failure : function(form, action) {
									Ext.getBody().unmask();
									Ext.MessageBox.alert('Warning', 'save failed, please try again.');
								}
							});
						}else{
							return;
						}
					});
					
				}
		}]});
	}
	
	if(!modelStore){
		Ext.define('models', {
			extend: 'Ext.data.Model',
			fields: ['modelId', 'modelName','subModelList']
		});
		var modelStore = Ext.create('Ext.data.Store', {
			model: 'models',
			proxy : new Ext.data.HttpProxy( {
				type: 'ajax',
				url : 'getModel.action?status=1',
				reader: {
					type: 'json',
					totalProperty : 'size',
					root : 'items',
					idProperty: 'modelId'
				}
			})
			
		});
		
		modelStore.on('load',function(){
			for(i=0;i<modelStore.getTotalCount();i++){
				var item,tltp = '';
				var subModelList = modelStore.getAt(i).data.subModelList;
				for(var subidx=0;subidx<subModelList.length;subidx++){
					tltp = tltp + subModelList[subidx].modelName + '<br/>';
				}
				var htmlText='<table width="100%" height="100%"><tr><td align="center"><img onClick="return false;" src="images/'+modelStore.getAt(i).data.modelId+'.gif" width="140" height="140">'+'</td></tr><tr><td align="center"><font size="2">'+modelStore.getAt(i).data.modelName+"</font></td></tr></table>";
				if(tltp==''){
					item = Ext.create('Ext.Button', {
						width:150,
						height:200,
						id:'btnModel'+modelStore.getAt(i).data.modelId,
						style: {
							marginTop:'10px',
							marginLeft:'10px', 
							marginRight:'10px'
						},
						html: htmlText
					});
				}else{
					item = Ext.create('Ext.button.Button', {
						width:150,
						height:200,
						style: {
							marginTop: '10px'
						},
						tooltip: '<ul>'+tltp+'</ul>',
						id:'btnModel'+modelStore.getAt(i).data.modelId,
						arrowAlign:'bottom',
						style: {
							marginTop:'10px',
							marginLeft:'10px', 
							marginRight:'10px'
						},
						text: htmlText
					});
				}
				Ext.getCmp('modelFieldset').add(item);
				
				item.getEl().on('click', function(e,t,eOpts){
					addSelectModel(Ext.getCmp('selectedFieldset'),Ext.getCmp(this.id).getText());
				});
			}
			Ext.getCmp('modelFieldset').doLayout();
		});
		
		modelStore.load();
	}
	
	Ext.getBody().mask('loading data...');
	Ext.Ajax.request({
		url: 'getGeneralInfo.action',
		success: function(response){
			var detail = Ext.util.JSON.decode(response.responseText);
			if(detail.selectedModels!=null&&detail.selectedModels.length>0){
				for(var idx=0;idx<detail.selectedModels.length;idx++){
					var htmlText='<table width="100%" height="100%"><tr><td align="center"><img onClick="return false;" src="images/'+detail.selectedModels[idx].modelId+'.gif" width="140" height="140">'+'</td></tr><tr><td align="center"><font size="2">'+detail.selectedModels[idx].modelName+"</font></td></tr></table>";
					addSelectModel(Ext.getCmp('selectedFieldset'),htmlText);
				}
			}
			if(detail.generalInfo){
				Ext.getCmp('customerSelect').setValue(detail.generalInfo.customer);
				Ext.getCmp('projectSelect').setValue(detail.generalInfo.project);
				Ext.getCmp('productSelect').setValue(detail.generalInfo.product);
				Ext.getCmp('plantSelect').setValue(detail.generalInfo.plant);
				Ext.getCmp('phaseSelect').setValue(detail.generalInfo.phase);
				Ext.getCmp('testPurpose').setValue(detail.generalInfo.testPurpose);
				Ext.getCmp('prjNumber').setValue(detail.generalInfo.projectNumber);
				Ext.getCmp('reportModeSelect').setValue(detail.generalInfo.reportMode);
				Ext.getCmp('reportDistrSelect').setValue(detail.generalInfo.reportDistribution);
				if(detail.generalInfo.testUser){
					Ext.getCmp('testUserSelect').setValue(detail.generalInfo.testUser.userId);
				}
				if(detail.generalInfo.vvUser){
					Ext.getCmp('vvUserSelect').setValue(detail.generalInfo.vvUser.userId);
				}
				Ext.getCmp('payer').setValue(detail.generalInfo.payer);
			}
			Ext.getBody().unmask();
			if(detail.readOnly==true){
				generalInfoPanel.setDisabled(true);
			}
		},
		failure: function(response){
			Ext.getBody().unmask();
			Ext.MessageBox.alert('Warning', 'Send mail failed, please try again.');
			generalInfoPanel.setDisabled(true);
		}
	});
})

</script>


<%@ include file="footer.jsp"%>